package handler

import (
	"errors"
	"fmt"
	"gmfs/core/storage"
	"gmfs/core/storage/mgoconf"
	"gmfs/core/tools/pic"
	"gmfs/core/tools/uid"
	"gmfs/core/tools/util"
	"gmfs/core/web/ink"
	"gmfs/core/web/model"
	"gopkg.in/mgo.v2"
	"image"
	"net/url"
	"strings"
)

var Connection *mgo.Session

/**
 * 欢迎界面
 */
func Welcome(ctx *ink.Context) {
	ctx.Body = []byte("Welcome gmfs.")
}

/**
 * 演示 Demo
 * http://localhost:1323/demo.html
 */
func Demo(ctx *ink.Context) {
	ctx.Render("demo", nil)
}

/**
 * 文件转正
 * http://localhost:1323/online/55c83f2a07986a0838000003/L5Ap4.html
 */
func Online(ctx *ink.Context) {
	id := ctx.Param("id")
	rdm := ctx.Param("rdm")
	var rlt = false
	var code = model.MSG_SUCCESS
	err := storage.UpdateInfoOnline(Connection, id, rdm)
	if err == nil {
		rlt = true
		code = model.MSG_ERROR
	}
	Json(ctx, code).Set("message", rlt).End()
}

/**
 * 初始化 gridfs
 */
func InitGridfs(cfgJson string) {
	cfg, err := mgoconf.Read(cfgJson)
	if err != nil {
		panic(err)
	}

	Connection, err = cfg.Connect()
	if err != nil {
		panic(err)
	}
}

/**
 * 初始化 cache
 */
func InitCache(start bool) {
	fmt.Println("initCache", start)
}

/**
 * 返回 JSON 信息
 */
func JsonInfo(ctx *ink.Context, code, mime, suffix, rdm, msg string) {
	Json(ctx, code).Set("mime", mime).Set("suffix", suffix).Set("rdm", rdm).Set("message", msg).End()
}

/**
 * 判断请求是否合法
 * 根据请求 referer 防止盗链
 */
func allowReq(ctx *ink.Context) (allow bool) {
	var rawurl = ctx.Referer
	if rawurl == "" {
		//测试的时候 referer 为空，返回 true
		return true
	}
	var domain = ctx.App().Config().StringOr("app.domain", "localhost")
	var subdomain string
	u, err := url.Parse(rawurl)
	if err != nil {
		return false
	}
	ll := strings.Split(u.Host, ".")
	if len(ll) >= 3 {
		subdomain = ll[1] + "." + ll[2]
	} else {
		subdomain = u.Host
	}

	var rlt = false
	d := strings.Split(domain, ";")
	for i := 0; i < len(d); i++ {
		if strings.EqualFold(subdomain, d[i]) {
			rlt = true
			break
		}
	}

	return rlt
}

/**
 * 保存图片到硬盘
 */
func saveImageToDisk(ctx *ink.Context, img image.Image, suffix string) (string, error) {
	//gif 保存为 jpg 格式
	if suffix == "gif" {
		suffix = "jpg"
	}

	//检查上传目录
	parent := ctx.App().Config().StringOr("file.upload_path", "./upload/")
	if !util.PathExist(parent) {
		if !util.Mkdir(parent) {
			return "", errors.New("mkdir upload_path error.")
		}
	}

	file_path := fmt.Sprintf("%s%x.%s", parent, uid.NextId(), suffix)
	err := pic.SaveImage(img, file_path)
	return file_path, err
}
